package org.net.httpclient
{
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	public class HttpTimer
	{
		private var _timer:Timer;
		
		private var _timeout:Number = 1 * 60 * 1000;
		private var _onTimeout:Function;
		private var _lastSeen:Number = -1;
		
		
	   /**
		* Timer.
		* @param timeout
		* @param onTimeout 
		*/
		public function HttpTimer(timeout:Number, onTimeout:Function)
		{
			if (timeout <= 0) 
				throw new ArgumentError("Timeout should be greater than 0");
			
			_timeout = timeout;
			_onTimeout = onTimeout;
			_timer = new Timer(1000);
			_timer.addEventListener(TimerEvent.TIMER, onTimer);
		}
		
		
		public function onTimer(event:TimerEvent):void {
			var idleTime:Number = now - _lastSeen;
			trace(idleTime);
			if (idleTime > _timeout) {
				_onTimeout(idleTime);
				reset();
			}
		}
		
		
		public function get now():Number {
			return new Date().time;
		}
		
		
		public function reset():void {
			_lastSeen = new Date().time;
		}
		
		
		public function start():void {
			reset();
			_timer.start();
		}
		
		public function stop():void {
			_timer.stop();
		}
	}
}